using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using MvcExtExample.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MvcExtExample.Handlers
{
    /// <summary>
    /// Summary description for LogHistoryOperation
    /// </summary>
    public class ErrorLogOperation : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string act = context.Request.Params["act"] ?? "";
            string output = "";
            switch (act.ToLower())
            {
                case "add":
                    output = Add(context.Request);
                    break;
                case "del":
                    output = Del(context.Request);
                    break;
                case "edit":
                    output = Edit(context.Request);
                    break;
                case "read":
                    output = Read(context.Request);
                    break;
                default:
                    output = "{'success':false,'msg':'错误的操作类型'}";
                    break;
            }
            context.Response.ContentType = "text/javascript";
            context.Response.Write(output);
        }

        private string Read(HttpRequest Request)
        {
            int start = 0;
            int TotalRecords;
            int.TryParse(Request.Params["start"], out start);
            StringBuilder strSqlStr = new StringBuilder();
            string total = "SELECT COUNT(*) FROM [dbo].[Tb_LogOperation] where OperationType IS NULL ";
            string sql1;
            if (start > 0)
            {
                sql1 = "SELECT TOP 5 * FROM( SELECT * FROM [dbo].[Tb_LogOperation] where OperationType IS NULL ) AS a WHERE a.[ID]>(SELECT MAX([ID]) FROM [dbo].[Tb_LogOperation] WHERE [ID] IN (SELECT TOP " + start + " [ID] FROM [dbo].[Tb_LogOperation])) ";
            }
            else
            {
                sql1 = "SELECT TOP 5 *FROM ( SELECT * FROM [dbo].[Tb_LogOperation] where OperationType IS NULL) AS a where 1=1";
            }
            if (Request.Params["filter"] != null)
            {
                string filter = "", op = "", BusinessesName = "";
                JArray jaf = JArray.Parse(Request.Params["filter"]);
                foreach (JObject jo in jaf)
                {
                    if ((string)jo["property"] == "op")
                        op = (string)jo["value"];
                    if ((string)jo["property"] == "BusinessesName")
                    {
                        BusinessesName = (string)jo["value"];
                        sql1 = sql1.Replace("OperationType", "BusinessesName");
                        sql1 = sql1.Replace("!=", "=");
                        sql1 = sql1.Replace("登录", BusinessesName);
                        total = total.Replace("OperationType", "BusinessesName");
                        total = total.Replace("!=", "=");
                        total = total.Replace("登录", BusinessesName);
                    }
                }
                strSqlStr.Append(sql1);
                sql1 = String.Empty;

                if (op != null)
                {
                    if (op.Length > 0)
                    {
                        DateTime startDate = new DateTime();
                        DateTime endDate = new DateTime();
                        foreach (JObject jo in jaf)
                        {
                            if ((string)jo["property"] == "startDate")
                            {
                                if (!String.IsNullOrEmpty(jo["value"].ToString()))
                                    startDate = Convert.ToDateTime(jo["value"].ToString());
                            }
                            if ((string)jo["property"] == "endDate")
                            {
                                if (!String.IsNullOrEmpty(jo["value"].ToString()))
                                    endDate = Convert.ToDateTime(jo["value"].ToString());
                            }
                        }
                        if (op == "=")
                        {
                            filter += " and  CreateTime ='" + startDate.ToString("yyyy-MM-dd HH:mm:ss") + "' ";
                        }
                        else
                        {
                            filter += String.Format(" and  CreateTime between '{0}' and '{1}' ", startDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                }

                foreach (JObject jo in jaf)
                {
                    if ((string)jo["property"] != "startDate" && (string)jo["property"] != "endDate" && (string)jo["property"] != "op")
                    {
                        filter += " AND " + (string)jo["property"] + " LIKE '%" + (string)jo["value"] + "%' ";
                    }
                }
                filter = filter.Substring(0, filter.Length - 1);
                strSqlStr.Append(filter.ToString());
            }
            strSqlStr.Append(sql1);
            framework.SqlHelperCS.SqlHelper cs = new framework.SqlHelperCS.SqlHelper();
            TotalRecords = cs.ReturnSQL(total);
            DataSet DSet = cs.GetDataSet(strSqlStr.ToString());
            if (DSet != null)
            {
                DataTable dt = DSet.Tables[0];
                StringBuilder JsonString = new StringBuilder();
                if (dt != null && dt.Rows.Count > 0)
                {
                    JsonString.Append("{\"total\":" + TotalRecords + ",\"data\":[ ");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        JsonString.Append("{ ");
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (j < dt.Columns.Count - 1)
                            {
                                JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\"" + ":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                            }
                            else if (j == dt.Columns.Count - 1)
                            {
                                JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\"" + ":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                            }
                        }

                        if (i == dt.Rows.Count - 1)
                        {
                            JsonString.Append("} ");
                        }
                        else
                        {
                            JsonString.Append("}, ");
                        }
                    }
                    JsonString.Append("]}");
                    return JsonString.ToString();
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        private string Edit(HttpRequest httpRequest)
        {
            throw new NotImplementedException();
        }

        private string Add(HttpRequest httpRequest)
        {
            throw new NotImplementedException();
        }

        private string Del(HttpRequest httpRequest)
        {

            string data = httpRequest.Params["data"] ?? "";
            List<Log> logs = new List<Log>();
            if (data.Length > 0)
            {
                logs = ProcessData(data);
                try
                {
                    foreach (Log item in logs)
                    {
                        string sql = "DELETE FROM [dbo].[Tb_LogOperation] WHERE [ID]='" + item.ID + "'";
                        framework.SqlHelperCS.SqlHelper cs = new framework.SqlHelperCS.SqlHelper();
                        cs.RunSQL(sql);
                    }
                    return "{'success':true}";
                }
                catch (Exception e)
                {
                    return "{'success':false,'Msg':'" + e.Message + "'}";
                }
            }
            else
            {
                return "{'success':false,'Msg':'错误的提交数据！'}";
            }
        }

        private List<Log> ProcessData(string data)
        {
            List<Log> logs = new List<Log>();
            logs = JsonConvert.DeserializeObject<List<Log>>(data);
            return logs;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}